# -*- encoding: utf-8 -*-
# @Time       :  20:48
# @Author     : yuxian
# @Email      : 1503889663@qq.com
# @File       : serializers.py
# @SoftWare   : PyCharm
import re
import cn2an
from django.db.models import Q
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer
from .models import Word, ImageData, Explain, Describe
from django.db.models.query import QuerySet
from variant_character.serializers import SimilarCharacterSerializer
from variant_character.models import SimilarCharacter


class ImageDataSerializer(ModelSerializer):
    class Meta:
        model = ImageData
        fields = "__all__"
        extra_kwargs = {
            'parent': {
                'write_only': True
            }
        }


class ParentSerializer(ModelSerializer):
    imagedata_set = ImageDataSerializer(many=True, read_only=True)

    class Meta:
        model = ImageData
        fields = "__all__"


class ExplainSerializer(ModelSerializer):
    class Meta:
        model = Explain
        fields = "__all__"


class DescribeSerializer(ModelSerializer):
    class Meta:
        model = Describe
        fields = "__all__"


class WordSerializer(ModelSerializer):
    image_urls = SerializerMethodField()
    Similar_character = SerializerMethodField()
    word_explain = ExplainSerializer(read_only=True)
    otherInfo = DescribeSerializer(read_only=True)

    class Meta:
        model = Word
        fields = "__all__"

    def utils(self, obj):
        book, name, file_label = tuple(obj.file_label.split("/"))
        a = re.findall("第(.*?)卷", file_label)[0]
        if a.isdigit():
            number = int(a)
        else:
            number = cn2an.cn2an(a)
        try:
            data = ImageData.objects.get(name=book)
        except ImageData.DoesNotExist:
            return None
        version_list = ImageData.objects.filter(Q(parent_id=data.id))
        image_data_list = []
        for version in version_list:
            data = ImageData.objects.filter(Q(parent_id=version.id) & Q(name__startswith=name))
            version_data = []
            for i in data:
                for num in re.findall(f"{name}_(\d+?)-(\d+?)", i.name):
                    start, end = tuple(num)
                    if int(start) <= number <= int(end):
                        version_data.append(i.save_id)
            image_data_list.append([version.name, version_data])
        return image_data_list

    def get_image_urls(self, words):
        need_data = []
        if isinstance(words, QuerySet):
            for word_1 in words:
                data = self.utils(word_1)
                if data:
                    need_data.extend(data)
        else:
            data = self.utils(words)
            if data:
                need_data.extend(data)
        return need_data

    def get_Similar_character(self, character):
        return_data = dict()
        if character.Similar_character:
            data = list(set(character.Similar_character[1:].split(";")))
            for i in data:
                parentid,id_ = i.split("_")
                char_set = SimilarCharacter.objects.filter(parent_id=parentid)
                if not char_set:
                    continue
                data = SimilarCharacterSerializer(char_set,many=True)
                return_data[id_] = data.data
        return return_data
